package com.csj.mvvmtest.ui

import android.content.Intent
import android.content.res.Configuration
import android.os.Handler
import android.view.KeyEvent
import android.widget.RadioGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.csj.mvvm.App
import com.csj.mvvm.bean.NotifyEntity
import com.csj.mvvm.event.EventCode
import com.csj.mvvm.event.EventMessage
import com.csj.mvvm.ui.base.BaseActivity2
import com.csj.mvvm.ui.base.BaseViewModel
import com.csj.mvvm.ui.base.StartAct.onStart
import com.csj.mvvm.utils.*
import com.csj.mvvm.version.AppDownloadManager
import com.csj.mvvm.widget.clicks
import com.csj.mvvmtest.R
import com.csj.mvvmtest.databinding.ActivityMainBinding
import com.csj.mvvmtest.ui.demo.MsgDetailActivity
import com.csj.mvvmtest.ui.first.FirstFragment
import com.csj.mvvmtest.ui.fourth.FourthFragment
import com.csj.mvvmtest.ui.second.SecondFragment
import com.csj.mvvmtest.ui.third.ThirdFragment
import com.csj.mvvm.utils.LogUtil
import com.csj.mvvmtest.util.IDUtil
import com.csj.mvvm.version.AppDownloadManager as DM


class MainActivity : BaseActivity2<BaseViewModel, ActivityMainBinding>(),
    RadioGroup.OnCheckedChangeListener {

    var mDownLoadManage: DM? = null
    private var isExit = false

    /**
     * 首页
     */
    private val TAB_FIRST = 1
    private var firstFragment: FirstFragment? = null

    /**
     * 收益
     */
    private val TAB_SECOND = 2
    private var secondFragment: SecondFragment? = null

    /**
     * 社区
     */
    private val TAB_THIRD = 3
    private var thirdFragment: ThirdFragment? = null

    /**
     * 我的
     */
    private val TAB_FOURTH = 4
    private var fourthFragment: FourthFragment? = null

    //当前Fragment
    private var mFragment: Fragment? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun initClick() {
        v.centerRb.clicks { ToastUtil.showToast("中心按钮点击") }
        v.radioGroup.setOnCheckedChangeListener(this)
    }


    override fun initData() {
        replaceView(TAB_FIRST)
        mDownLoadManage = AppDownloadManager.getInstance(mContext)
        mDownLoadManage?.create()
        //放最后，判断进入消息中心
        toDetail()
//        LogUtil.e(TimeUtil.dayOfYear(5,20,2020).toString())
//        LogUtil.e(TimeUtil.dayOfYear(5,20).toString())
        IDUtil.getGAID()
        IDUtil.getAndroidId()
    }

    override fun initVM() {

    }

    private fun toDetail() {
        val extras = intent.getBundleExtra(IntentExtras.IS_NEW_OPEN)
        if (extras != null && extras.getBoolean(IntentExtras.KILL)) {
            //有消息过来直接进入消息中心
            val notifyEntity = extras.getSerializable(IntentExtras.APS_DATA) as NotifyEntity?
            if (notifyEntity!!.type == 3) {
                onStart<MsgDetailActivity>(mContext)
            }
        }
    }

    /**
     * 接收消息
     */
    override fun handleEvent(msg: EventMessage) {
        super.handleEvent(msg)
        if (msg.code == EventCode.REFRESH) {
            Handler().postDelayed({ ToastUtil.showToast("主页：刷新") }, 2000)
        }
    }

    override fun onDestroy() {
        mDownLoadManage?.destroy()
        super.onDestroy()
    }

    /**
     * 切换视图
     *
     * @param currItem the curr item
     */
    @Synchronized
    private fun replaceView(currItem: Int) {
        val transaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        if (mFragment != null) {
            transaction.hide(mFragment!!)
        }
        when (currItem) {
            TAB_FIRST -> {
                v.centerRb.isChecked = false
                if (firstFragment == null) {
                    if (supportFragmentManager.findFragmentByTag("firstFragment") == null) {
                        firstFragment = FirstFragment()
                        transaction.add(v.frameLayout.id, firstFragment!!, "firstFragment")
                    } else {
                        firstFragment =
                            supportFragmentManager.findFragmentByTag("firstFragment") as FirstFragment?
                        transaction.replace(v.frameLayout.id, firstFragment!!, "firstFragment")
                    }

                }
                mFragment = firstFragment
            }
            TAB_SECOND -> {
                v.centerRb.isChecked = false
                if (secondFragment == null) {
                    if (supportFragmentManager.findFragmentByTag("secondFragment") == null) {
                        secondFragment = SecondFragment()
                        transaction.add(v.frameLayout.id, secondFragment!!, "secondFragment")
                    } else {
                        secondFragment =
                            supportFragmentManager.findFragmentByTag("secondFragment") as SecondFragment?
                        transaction.replace(v.frameLayout.id, secondFragment!!, "secondFragment")
                    }
                }
                mFragment = secondFragment
            }
            TAB_THIRD -> {
                v.centerRb.isChecked = false
                if (thirdFragment == null) {
                    if (supportFragmentManager.findFragmentByTag("thirdFragment") == null) {
                        thirdFragment = ThirdFragment()
                        transaction.add(v.frameLayout.id, thirdFragment!!, "thirdFragment")
                    } else {
                        thirdFragment =
                            supportFragmentManager.findFragmentByTag("thirdFragment") as ThirdFragment?
                        transaction.replace(v.frameLayout.id, thirdFragment!!, "thirdFragment")
                    }
                }
                mFragment = thirdFragment
            }
            TAB_FOURTH -> {
                v.centerRb.isChecked = false
                if (fourthFragment == null) {
                    if (supportFragmentManager.findFragmentByTag("fourthFragment") == null) {
                        fourthFragment = FourthFragment()
                        transaction.add(v.frameLayout.id, fourthFragment!!, "fourthFragment")
                    } else {
                        fourthFragment =
                            supportFragmentManager.findFragmentByTag("fourthFragment") as FourthFragment?
                        transaction.replace(v.frameLayout.id, fourthFragment!!, "fourthFragment")
                    }
                }
                mFragment = fourthFragment
            }
        }
        mFragment?.let { transaction.show(it) }
        transaction.commitAllowingStateLoss()
    }

    override fun onCheckedChanged(p0: RadioGroup?, checkedId: Int) {
        when (checkedId) {
            v.firstRb.id -> replaceView(TAB_FIRST)
            v.secondRb.id -> replaceView(TAB_SECOND)
            v.thirdRb.id -> replaceView(TAB_THIRD)
            v.fourthRb.id -> replaceView(TAB_FOURTH)
        }
    }

    private var handler: Handler? = null
    private var runnable: Runnable? = null

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isExit) {
                finish()
            } else {
                ToastUtil.showToast("再按一次退出程序")
                isExit = true
                if (handler == null) {
                    handler = Handler()
                    runnable = Runnable { isExit = false }
                }
                handler!!.postDelayed(runnable!!, 3000)
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        when (newConfig.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
            Configuration.UI_MODE_NIGHT_NO -> {
                // Night mode is not active, we're using the light theme
                LogUtil.d("onConfigurationChanged: light")
                if (NightModeUtil.getSystemMode()) {
                    StatusBarUtil2.setTranslucentStatus(this, true)
                    NightModeUtil.initNightMode(false)
                    if (App.isNightInit) {
                        NightModeUtil.restartApp(mContext, Intent(mContext, MainActivity::class.java))
                    }
                }
//                AppTheme.update(Themes.Day)
            }

            Configuration.UI_MODE_NIGHT_YES -> {
                // Night mode is active, we're using dark theme
                LogUtil.d("onConfigurationChanged: dark")
                if (NightModeUtil.getSystemMode()) {
                    StatusBarUtil2.setTranslucentStatus(this, false)
                    NightModeUtil.initNightMode(true)
                }
//                AppTheme.update(Themes.Night)
            }

        }
    }

}